import tkinter
import socket #导入TCP库
import threading
import datetime
from tkinter import messagebox
import os


status = 0
# http://tt.ai-thinker.com:8000/ttcloud    安信可透传云，测试TCP
def main_fun():
    global status
    global TCP_Client_Socket
    # 1.创建TCP套接字
    TCP_Client_Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 2.连接TCP服务器
    try:
        # TCP_Client_Socket.connect(('122.114.122.174', 41645))
        # TCP_Client_Socket.connect(('127.0.0.1', 9980))
        server_ip = server_ip_entry.get()
        sever_port = int(server_port_entry.get())
        sever_addr = (server_ip, sever_port)
        TCP_Client_Socket.connect(sever_addr)
        # print('连接服务器成功')
        status_label.config(text='连接服务器成功', bg='lightgreen')
        status = 1
        # 3.发数据收数据
        # send_data = input('请输入要发给客户端的数据：')
        # TCP_Client_Socket.send(send_data.encode())
        # 串口测试

        # 4.数据处理
        try:
            while status == 1:
                if status == 0:
                    break
                msg = TCP_Client_Socket.recv(1024)
                if not msg:
                    break
                val = msg.decode('utf-8')
                # print('监听到服务器的数据是：')
                # print(val)
                val1 = str(datetime.datetime.now()) + '   tcp received\n' + str(val) + '\n'
                received_text.insert('end', val1)
        except:
            status = 0
            messagebox.showwarning(title='warning', message='连接已断开')
        # # 关闭套接字
        # TCP_Client_Socket.close()
        # # print('套接字关闭')
        # status_label.config(text='服务器已断开连接', bg='yellow')
        # status = 0
    except TimeoutError:
        # print('连接服务器失败')
        status_label.config(text='连接服务器失败', bg='pink')
        status = 0
    except Exception as ex:
        # print(str(ex))
        status = 0
        messagebox.showerror(title='error', message=str(ex))


def thread_main_fun():
    thread_add1 = threading.Thread(target=main_fun)
    thread_add1.start()


def send_message():
    if status == 1:
        send_data = send_text.get(0.0, 'end')
        TCP_Client_Socket.send(send_data.encode())
    else:
        messagebox.showwarning(title='warning', message='请先连接服务器')


def disconnect():
    try:
        global status
        status = 0
        # 关闭套接字
        TCP_Client_Socket.close()
        # print('套接字关闭')
        status_label.config(text='套接字已关闭', bg='yellow')
    except Exception as ex:
        messagebox.showerror(title='error', message=str(ex))



win = tkinter.Tk()
win.title('TCP client-side           Author : Shi Sixian')
win.geometry('780x400')
win.option_add('*Font', '宋体 10')

server_ip_label = tkinter.Label(win, text='ServerIP:')
server_ip_label.place(x=20, y=20)
server_ip_entry = tkinter.Entry(win, width=20)
server_ip_entry.place(x=90, y=20)
server_port_label = tkinter.Label(win, text='ServerPort:')
server_port_label.place(x=250, y=20)
server_port_entry = tkinter.Entry(win, width=10)
server_port_entry.place(x=335, y=20)
server_ip_entry.insert('end', '127.0.0.1')
server_port_entry.insert('end', '61234')
connect_button = tkinter.Button(win, text='Connect', command=thread_main_fun)
connect_button.place(x=410, y=17)
disconnect_button = tkinter.Button(win, text='Disconnect', command=disconnect)
disconnect_button.place(x=490, y=17)
status_label = tkinter.Label(win, text='等待连接服务器', bg='yellow', width=25)
status_label.place(x=580, y=20)

frame1 = tkinter.Frame(win, width=360, height=330, bg='ivory')
frame1.place(x=20, y=50)
frame2 = tkinter.Frame(win, width=360, height=330, bg='ivory')
frame2.place(x=400, y=50)

send_label = tkinter.Label(frame1, text='Send massage to the server-side', bg='ivory')
send_label.place(x=5, y=5)
send_button = tkinter.Button(frame1, text='Send', command=send_message)
send_button.place(x=300, y=2)
send_text = tkinter.Text(frame1, width=49, height=23)
send_text.place(x=5, y=25)

received_label = tkinter.Label(frame2, text='Received massage from the server-side', bg='ivory')
received_label.place(x=5, y=5)
received_text = tkinter.Text(frame2, width=49, height=23)
received_text.place(x=5, y=25)


def quit1():
    os._exit(0)


win.resizable(False, False)
win.protocol("WM_DELETE_WINDOW", quit1)
win.mainloop()
